# -*- coding: utf-8 -*-
import json
from collections import OrderedDict

import requests
from alipay import AliPay

from async import async_job
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_alipay = AliPay(
    appid="2018010801687525",
    app_notify_url='http://notify.bookstore888.com:8888/notify/',
    app_private_key_path='/opt/our_alipay/ali_loki/ali_private_key_pkcs8.pem',
    alipay_public_key_path='/opt/our_alipay/ali_loki/ali_public_key.pem',
    sign_type='RSA2'
)

_alipay_witch = AliPay(
    appid="2017122701271436",
    app_notify_url='http://notify.zhumengbookstore.com:8888/notify/',
    app_private_key_path='/opt/our_alipay/ali_witch/ali_private_key_pkcs8.pem',
    alipay_public_key_path='/opt/our_alipay/ali_witch/ali_public_key.pem',
    sign_type='RSA2'
)

_alipay_loki2 = AliPay(
    appid="2018011801948930",
    app_notify_url='http://120.79.89.43:8888/notify/',
    app_private_key_path='/opt/our_alipay/ali_loki2/ali_private_key_pkcs8.pem',
    alipay_public_key_path='/opt/our_alipay/ali_loki2/ali_public_key.pem',
    sign_type='RSA2'
)

_alipay_loki3 = AliPay(
    appid="2018011801949114",
    app_notify_url='http://120.79.133.212:8888/notify/',
    app_private_key_path='/opt/our_alipay/ali_loki3/ali_private_key_pkcs8.pem',
    alipay_public_key_path='/opt/our_alipay/ali_loki3/ali_public_key.pem',
    sign_type='RSA2'
)

_alipay_loki4 = AliPay(
    appid="2018012702092196",
    app_notify_url='http://120.79.129.53:8888/notify/',
    app_private_key_path='/opt/our_alipay/ali_loki4/ali_private_key_pkcs8.pem',
    alipay_public_key_path='/opt/our_alipay/ali_loki4/ali_public_key.pem',
    sign_type='RSA2'
)

_alipay_loki5 = AliPay(
    appid="2018012702092108",
    app_notify_url='http://39.108.158.156:8888/notify/',
    app_private_key_path='/opt/our_alipay/ali_loki5/ali_private_key_pkcs8.pem',
    alipay_public_key_path='/opt/our_alipay/ali_loki5/ali_public_key.pem',
    sign_type='RSA2'
)

_alipay_loki6 = AliPay(
    appid="2018012702092317",
    app_notify_url='http://120.79.193.225:8888/notify/',
    app_private_key_path='/opt/our_alipay/ali_loki6/ali_private_key_pkcs8.pem',
    alipay_public_key_path='/opt/our_alipay/ali_loki6/ali_public_key.pem',
    sign_type='RSA2'
)

_alipay_loki7 = AliPay(
    appid="2018020402140894",
    app_notify_url='http://120.79.196.176:8888/notify/',
    app_private_key_path='/opt/our_alipay/ali_loki7/ali_private_key_pkcs8.pem',
    alipay_public_key_path='/opt/our_alipay/ali_loki7/ali_public_key.pem',
    sign_type='RSA2'
)

_alipay_loki8 = AliPay(
    appid="2018020402140856",
    app_notify_url='http://120.79.94.172:8888/notify/',
    app_private_key_path='/opt/our_alipay/ali_loki8/ali_private_key_pkcs8.pem',
    alipay_public_key_path='/opt/our_alipay/ali_loki8/ali_public_key.pem',
    sign_type='RSA2'
)

_alipay_loki9 = AliPay(
    appid="2018020602149476",
    app_notify_url='http://120.79.176.125:8888/notify/',
    app_private_key_path='/opt/our_alipay/ali_loki9/ali_private_key_pkcs8.pem',
    alipay_public_key_path='/opt/our_alipay/ali_loki9/ali_public_key.pem',
    sign_type='RSA2'
)

APP_CONF = {
    '2018010801687525': {
        'handle': _alipay,
        'gateway': 'http://notify.bookstore888.com:8889/alipay',
        'return_url': 'http://www.bookstore888.com/',
    },
    '2017122701271436': {
        'handle': _alipay_witch,
        'gateway': 'http://notify.zhumengbookstore.com:8889/alipay',
        'return_url': 'http://www.zhumengbookstore.com/',
    },
    '2018011801948930': {
        'handle': _alipay_loki2,
        'gateway': 'http://120.79.89.43:8889/alipay',
        'return_url': 'http://www.baidu.com/',
    },
    '2018011801949114': {
        'handle': _alipay_loki3,
        'gateway': 'http://120.79.133.212:8889/alipay',
        'return_url': 'http://www.baidu.com/',
    },
    '2018012702092196': {
        'handle': _alipay_loki4,
        'gateway': 'http://120.79.129.53:8889/alipay',
        'return_url': 'http://www.baidu.com/',
    },
    '2018012702092108': {
        'handle': _alipay_loki5,
        'gateway': 'http://39.108.158.156:8889/alipay',
        'return_url': 'http://www.baidu.com/',
    },
    '2018012702092317': {
        'handle': _alipay_loki6,
        'gateway': 'http://120.79.193.225:8889/alipay',
        'return_url': 'http://www.baidu.com/',
    },
    '2018020402140894': {
        'handle': _alipay_loki7,
        'gateway': 'http://120.79.196.176:8889/alipay',
        'return_url': 'http://www.baidu.com/',
    },
    '2018020402140856': {
        'handle': _alipay_loki8,
        'gateway': 'http://120.79.94.172:8889/alipay',
        'return_url': 'http://www.baidu.com/',
    },
    '2018020602149476': {
        'handle': _alipay_loki9,
        'gateway': 'http://120.79.176.125:8889/alipay',
        'return_url': 'http://www.baidu.com/',
    },
}


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_handle(mch_id):
    return APP_CONF[mch_id]['handle']


def _get_return_url(mch_id):
    return APP_CONF[mch_id]['return_url']


def create_charge(pay, pay_amount, info):
    alipay_type = info.get('alipay_type') or ''
    app_id = info['app_id']
    parameter_dict = OrderedDict((
        ('alipay_type', alipay_type),
        ('subject', 'buy_book'),
        ('out_trade_no', str(pay.id)),
        ('total_amount', str(pay_amount)),
        ('return_url', _get_return_url(app_id)),
    ))
    _LOGGER.info("our_alipay create data: %s", parameter_dict)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=10)
    _LOGGER.info("our_alipay rsp data: %s", response.text)
    res_obj = json.loads(response.text)
    return {'charge_info': res_obj['url']}


def verify_notify_sign(data, the_alipay):
    signature = data.pop("sign")
    success = the_alipay.verify(data, signature)
    if not success:
        _LOGGER.info("our_alipay sign not pass :%s", data)
        raise ParamError('sign not pass, data: %s' % data)


def check_notify_sign(request):
    data = dict(request.POST.iteritems())
    _LOGGER.info("our_alipay notify data: %s", data)
    the_alipay = _get_handle(data['app_id'])
    verify_notify_sign(data, the_alipay)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('our_alipay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['trade_status']
    trade_no = data['trade_no']
    total_fee = float(data['total_amount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status in ("TRADE_SUCCESS", "TRADE_FINISHED"):
        _LOGGER.info('our_alipay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    the_alipay = _get_handle(app_id)
    response = the_alipay.api_alipay_trade_query(out_trade_no=str(pay_order.id))
    _LOGGER.info('our_alipay query rsp: %s' % response)
    trade_status = response['trade_status']
    trade_no = response['trade_no']
    total_fee = float(response['total_amount'])

    if trade_status in ("TRADE_SUCCESS", "TRADE_FINISHED"):
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        _LOGGER.info('our_alipay query order success, mch_id:%s pay_id:%s',
                     pay_order.mch_id, pay_order.id)
        add_pay_success(app_id, pay_order.id, total_fee, trade_no, extend)
        async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('our_alipay query order fail, status_code: %s', response)
